package com.attilax.lang;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import aaaCfg.IocX;

import com.attilax.atian.PinyinX;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.text.strUtil;
import com.attilax.util.dirx;

/**
 * dir recycleProcessor ... com.attilax.lang.RecycleProcessor
 * 
 * @author Administrator
 *
 */
public class RecycleProcessor {

	private String mainDir;
	public RecycleProcessor(String mainDir) {
		this.mainDir = mainDir;
	}
	public RecycleProcessor() {
	}
	static filex fx_pics;
	static String encode = "gbk";
	static 	String cfgFile;
	static 	String cates;
	static 	Set cates_set;
	public static void main(String[] args) throws IOException {
		String rzt_fileName = "c:\\scanMovRzt.csv";
		String rzt_fileName_pics = "c:\\scanMovRzt_onlypic.csv";
		RecycleProcessor rp = new RecycleProcessor();
		String scanpath = "z:";
	
		if (args.length > 0)
			scanpath = args[0];
		if (args.length >= 2)
			rzt_fileName = args[1].trim();
		 cfgFile=args[2].trim();
		if (args.length >= 3)
			encode = args[3].trim();
		
		try {
			cates=args[4].trim();
			cates_set=new HashSet<String>();
			String[] a=cates.trim().split(",");
			for (String string : a) {
				cates_set.add(string);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		final String first_video_fmt = "avi,vob,rmvb";
	

		final filex fx = new filex(rzt_fileName, "gbk");
		fx_pics = new filex(rzt_fileName_pics, "gbk");
		String title_line = "material_description,material_type,file_path,thumb,material_keyword,application_type,txt_file";
		System.out.println("line:" + title_line);
		fx.append_HP_Safe(title_line + "\r\n");

		final String scanpath_final = scanpath;
		rp.exe(scanpath, new Closure<String, Object>() {
			@Override
			public Object execute(String dirx) throws Exception {
				dirx=URLDecoder.decode(dirx, "utf-8");
				return exeSingle(first_video_fmt, fx, scanpath_final, dirx);
			}
		});
		System.out.println("---f");
	}

	public static Object exeSingle(final String first, final filex fx,
			final String scanpath, String dirx) throws IOException {
		String scanpath3 = scanpath.replaceAll("\\\\", "\\\\\\\\") + "\\\\";
		
		final String scanpath2 = scanpath3;
		System.out.println("dir:" + dirx);
		File dir = new File(dirx);
		
		//p93  only select cates scans
		if(cates_set!=null )
		{
			String cate=getCate(dir);
			if(!cates_set.contains(cate))
				return null;
		}
		File[] files = dir.listFiles();
		String line = "";
		String basename = "";
		String mkv = "";
		String thumb = "";
		String png = "";
		String txt = "";
		Map<String, String> movs_map = new HashMap();
		for (File fil : files) {

			
		
			fil.getCanonicalPath();// //z:\悬疑类\消失的爱人 豆瓣8.8
									// [大卫芬奇年度巨制，口碑爆棚！]\Gone.Girl.2014.1080p.BluRay.REMUX.AVC.DTS-HD
									// MA.1-CHD.nfo
			fil.getName();// aa.jpg
			fil.getParent();// z:\悬疑类\消失的爱人 豆瓣8.8 [大卫芬奇年度巨制，口碑爆棚！]
			fil.getPath();// z:\悬疑类\消失的爱人 豆瓣8.8
							// [大卫芬奇年度巨制，口碑爆棚！]\Gone.Girl.2014.1080p.BluRay.REMUX.AVC.DTS-HD
							// MA.1-CHD.nfo
			String f = fil.getAbsolutePath();
			if (f.contains("@Recycle"))
				continue;

			if (f.contains(",")) {
				String f2 = f.replaceAll(",", "");
				filex.rename(f, f2);
				f = f2;

			}

			/*
			 * .avi .m2ts .ts .iso .rmvb .mp4
			 */
			if (f.endsWith("mkv") || f.endsWith("mp4") || f.endsWith("ts")
					|| f.endsWith("m2ts") || f.endsWith("iso")
					|| f.endsWith("rmvb") || f.endsWith("avi")) {
				basename = filex.getFileName_noExtName(f);
				basename = getTitleName(basename, f);

				mkv = f;
				mkv = mkv.replaceAll(scanpath2, "");
				// mkv.substring(3);

			} else if (otherVideo(f, first))
				basename = setMovsMap(movs_map, first, f, scanpath2);

			if (f.endsWith("jpg")) {
				thumb = f.replaceAll(scanpath2, "");
			}
			if (f.endsWith("png")) {

				png = f.replaceAll(scanpath2, "");
			}
			if (f.endsWith("txt")) {
				txt = f.replaceAll(scanpath2, "");
			}

		}
		if (mkv.contains("喜爱夜蒲"))
			System.out.println("--");
		String cateID = "";

		mkv = getMkv(movs_map, first, mkv);

		try {
			cateID = getCateid(mkv);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (thumb.length() == 0)
			thumb = png;
		String pinyin = PinyinX.getSimple(basename);
		basename = basename.replaceAll(",", " ");
		line = basename + "," + cateID + "," + mkv + "," + thumb + "," + pinyin
				+ "," + cateID + "," + txt;
		System.out.println("line:" + line);
		fx_pics.append_HP_Safe(line + "\r\n");
		if (mkv.length() == 0)
			return null;
		fx.append_HP_Safe(line + "\r\n");
		return null;
	}

	private static String getCate(File fil) {
		String path=fil.getAbsolutePath();
		path=pathx.fixSlash(path);
		String[] a=path.split("/");
		
		return a[1];
	}
	private static boolean otherVideo(String f, String first) {
		String ext = filex.getExtName(f);
		String[] a = first.split(",");
		for (String mov_ext : a) {
			if (mov_ext.trim().toLowerCase().equals(ext.trim().toLowerCase()))
				return true;
		}
		return false;
	}

	protected static String getMkv(Map<String, String> movs_map, String first, String mkv) {
		if(mkv.length()>0)return mkv;
		 String[] a=first.split(",");
		 for (String mov_ext : a) {
			 if(movs_map.get(mov_ext)!=null)
				 return movs_map.get(mov_ext);
		 }
		return mkv;
	}

	protected static String setMovsMap(Map<String, String> movs_map,
			String first, String f, String replacePathHead) {
	 String[] a=first.split(",");
		String basename = "";
	 for (String mov_ext : a) {
			if (f.endsWith(mov_ext)  ) {
				basename = filex.getFileName_noExtName(f);
				basename = getTitleName(basename, f);

			String	mkv = f;
				mkv = mkv.replaceAll(replacePathHead, "");
				// mkv.substring(3);
				movs_map.put(mov_ext, mkv);

			}
	}
		return basename;
		
	}

	public static String getTitleName(String basename, String f) {
		if (f.contains("喜爱夜蒲"))
			System.out.println("--");
		if (!strUtil.isContainCnchar(basename))// basename.getBytes().length
												// ==
												// basename.length())
												// // en
			basename = getParentName(f);
		// if en start  rem on p93  cause  007：大破天幕杀机 豆瓣6.9
//		if (basename.length() > 3) {
//			String start2ch = basename.substring(0, 3);
//			if (!strUtil.isContainCnchar(start2ch))
//				basename = getParentName(f);
//		}

		if (basename.contains("豆瓣")) {
			int idx = basename.indexOf("豆瓣");
			basename = basename.substring(0, idx).trim();
		}
		if (basename.contains(".")) {
			// if (!strUtil.isContainCnchar(basename))
			{
				int idx = basename.indexOf(".");
				basename = basename.substring(0, idx).trim();
			}
		}
		return basename;
	}
	@SuppressWarnings("rawtypes")
	protected static String getCateid(String mkv) {
		int a = mkv.indexOf("\\");
		String trim = "";

		trim = mkv.substring(0, a).trim();

		String f =cfgFile;
				//pathx.classPath(IocX.class) + "\\cate.txt";
		Map m = YamlAtiX.getMapReverse(f);

		return (String) m.get(trim);
	}

	protected static String getParentName(String f) {
		if (f.contains("异能"))
			System.out.println("00");
		File f2 = new File(f);
		File prt = f2.getParentFile();

		String basename = "";
		try {
			basename = filex.getFileName_noExtName(prt.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!strUtil.isContainCnchar(basename)) // en
			return getParentName(prt.getAbsolutePath());
		// if en start  p93  rem
//		String start2ch = basename.substring(0, 3);
//		if (!strUtil.isContainCnchar(start2ch))
//			return getParentName(prt.getAbsolutePath());
		return prt.getName();
	}

	public void exe(String strPath, Closure<String, Object> closure) {
		com.attilax.io.dirx.traveDir(strPath, closure);

	}

}
